package com.hd123.rumba.gwt.widget2.client.fielddef;

/**
 * 字段定义
 * 
 * @author LiQi
 * 
 */
public class FieldDef {

  /** 名称 */
  protected String name;

  /** 标题 */
  protected String caption;

  /** 是否允许为空 */
  protected boolean nullable = true;

  public FieldDef() {

  }

  public FieldDef(String name, String caption, boolean nullable) {
    this.name = name;
    this.caption = caption;
    this.nullable = nullable;
  }

  public FieldDef clone() {
    return new FieldDef(name, caption, nullable);
  }

  /**
   * 验证传入的文本是否能合法的转换成字段的值，以及这个值是否合法。
   * 
   * @param text
   *          文本
   * @param message
   *          输出消息
   * @param checkNullable
   *          是否进行非空检查
   * @return 成功返回true，否则返回false
   */
  public boolean validateText(String text, StringBuffer message, boolean checkNullable) {
    return validate(text, message, checkNullable);
  }

  /**
   * 验证传入的文本是否能合法的转换成字段的值，以及这个值是否合法。
   * 
   * @param text
   * @return
   */
  public boolean validateText(String text, StringBuffer message) {
    return validateText(text, message, true);
  }

  /**
   * 验证传入的值是否合法
   * 
   * @param value
   * @return
   */
  public boolean validate(Object value, StringBuffer message) {
    return validate(value, message, true);
  }

  public boolean validate(Object value, StringBuffer message, boolean checkNullable) {
    boolean result = true;

    // nullable
    if (checkNullable) {
      if (!nullable && value == null) {
        appendMessage(message, "不允许空值");
        result = false;
      }
    }

    finalizeMessage(message);
    return result;
  }

  /**
   * 添加一条消息
   * 
   * @param newMessage
   */
  protected void appendMessage(StringBuffer message, String newMessage) {
    if (message == null)
      return;
    message.append(newMessage + "; ");
  }

  /**
   * 整理消息的格式，使之可以被返回给界面
   * 
   * @param message
   */
  protected void finalizeMessage(StringBuffer message) {
    if (message == null || message.length() == 0)
      return;
    String prefix = caption + "：";
    if (message.indexOf(prefix) == -1)
      message.insert(0, prefix);
  }

  protected void finalizeMessage(StringBuffer message, String newMessage) {
    appendMessage(message, newMessage);
    finalizeMessage(message);
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getCaption() {
    return caption;
  }

  public void setCaption(String caption) {
    this.caption = caption;
  }

  public boolean isNullable() {
    return nullable;
  }

  public boolean isRequired() {
    return !nullable;
  }

  public void setNullable(boolean nullable) {
    this.nullable = nullable;
  }

}
